package com.linx.common.translation.core.handler;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.linx.common.translation.annotation.TranslationGroup;
import com.linx.common.translation.core.TranslationInterface;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 翻译处理器
 *
 * @author Lion Li
 */
@Slf4j
public class TranslationGroupHandler extends JsonSerializer<Object> implements ContextualSerializer {

    /**
     * 全局翻译实现类映射器
     */
    public static final Map<String, TranslationInterface<?>> TRANSLATION_MAPPER = new ConcurrentHashMap<>();

    private TranslationGroup translationGroup;

    /**
     * 序列化方法
     * @param value 待序列化对象
     * @param gen 序列化器
     * @param serializers 序列化器提供者
     */
    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        log.info("开始翻译对象：{}", translationGroup.group());


    }

    /**
     * 创建上下文序列化器
     */
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        TranslationGroup translationGroup = property.getAnnotation(TranslationGroup.class);
        if (Objects.nonNull(translationGroup)) {
            this.translationGroup = translationGroup;
            return this;
        }
        return prov.findValueSerializer(property.getType(), property);
    }
}
